package com.brillilab.starter.controller.common;

import com.brillilab.common.entity.ResponseVo;
import com.brillilab.common.utils.ValidatorUtil;
import com.brillilab.domain.vo.user.UserInfoVo;
import com.brillilab.service.logic.message.MessageLogic;
import com.brillilab.service.logic.user.UsersLogic;
import com.brillilab.starter.constant.StarterConstant;
import com.brillilab.starter.entity.req.lab.SmsSendReq;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

/**
 * 短信发送Controller
 *
 * @author lj
 */
@RestController
@RequestMapping("/api/sms")
public class SmsSendController {

    @Autowired
    private MessageLogic messageLogic;
    @Autowired
    private UsersLogic usersLogic;

    /**
     * 发送通用短信验证码
     *
     * @return
     */
    @PostMapping("/smsCode")
    public ResponseVo sendVerifyCode(@RequestBody SmsSendReq req){
		String mobile = req.getMobile();
        Assert.isTrue(ValidatorUtil.isPhone(mobile),"请输入正确的手机号！");
        boolean b = messageLogic.sendVerifyCode(mobile);
        return b?ResponseVo.success():ResponseVo.failure();
    }

    /**
     * 发送短信验证码校验用户已注册
     * {\"mobile\":\"手机号 必填 S\"}
     *
     * @return
     */
    @PostMapping("/ckSmsCode")
    public ResponseVo sendVerifyCodeValidatePhone(@RequestBody SmsSendReq req,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Long labId=req.getLabId();
        String mobile=req.getMobile();

        if(!StringUtils.isBlank(token)){
            UserInfoVo userinfo=usersLogic.getUserByToken(token);
            labId = userinfo.getLabId();
        }

        Assert.isTrue(StringUtils.isNotBlank(mobile),"请输入手机号！");
        Assert.isTrue(ValidatorUtil.isPhone(mobile),"请输入正确的手机号！");

        // 判断用户是否存在
        usersLogic.getExistUser(labId,mobile);

        boolean b=messageLogic.sendVerifyCode(mobile);
        Assert.isTrue(b,"短信验证失败！");

        return ResponseVo.success();
    }

}
